package org.jeecg.modules.basic.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.demo.bed.entity.LwgyBaseBed;
import org.jeecg.modules.basic.demo.bed.service.ILwgyBaseBedService;
import org.jeecg.modules.basic.demo.student.entity.LwgyBaseStudent;
import org.jeecg.modules.basic.demo.student.service.ILwgyBaseStudentService;
import org.jeecg.modules.basic.entry.entity.LwgyAbnormalAction;
import org.jeecg.modules.basic.entry.service.ILwgyAbnormalActionService;
import org.jeecg.modules.basic.entry.service.ILwgyInoutRecordService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author sn
 * @date 2022-09-23 15:20
 *  //以5天为限，一直没出去的为--长时间未出（异常）
 *  一直没进来的为--长时间未归（异常）具体时间限制后期可以加到异常推送配置表中
 *
 */
@Slf4j
public class UnusualAbnormalInfoJob implements Job {

    @Autowired
    private ILwgyInoutRecordService lwgyInoutRecordService;

    @Autowired
    private ILwgyBaseStudentService lwgyBaseStudentService;

    @Autowired
    private ILwgyAbnormalActionService lwgyAbnormalActionService;

    @Autowired
    private ILwgyBaseBedService lwgyBaseBedService;


    @SneakyThrows
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info(String.format(" 时间:" + DateUtils.getTimestamp()));
        //得到一个Calendar实例
        Calendar calendar = Calendar.getInstance();
        //calendar的日期设为今天
        calendar.setTime(new Date());
        //五天前的凌晨
        calendar.add(Calendar.DATE, -5);
        Date day1 = calendar.getTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String pre = simpleDateFormat.format(day1);
        String startTime = pre.substring(0, 10) + " 00:00:00";
        //当天凌晨
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(new Date());
        calendar2.add(Calendar.DATE, -1);
        Date day2 = calendar2.getTime();
        String pre2 = simpleDateFormat.format(day2);
        String endTime = pre2.substring(0, 10) + " 00:00:00";


        QueryWrapper<LwgyBaseStudent> queryWrapper = new QueryWrapper<>();

        queryWrapper.ge("last_direction_time", startTime);
        queryWrapper.lt("last_direction_time", endTime);

        List<LwgyBaseStudent> wglist = lwgyBaseStudentService.getListByJob(queryWrapper);

        //循环wglist ,写入异常表
        if(wglist.size()>0){
            //  通过学生id获取原床位信息
            String[] ids = wglist.stream().map(p -> p.getId()).collect(Collectors.toList()).toArray(new String[0]);
            List<LwgyBaseBed> bedList = lwgyBaseBedService.getBedListByStuId2(ids);
            //获取学院信息床位信息end

            List<LwgyAbnormalAction> endList = new ArrayList<LwgyAbnormalAction>();
            wglist.stream().forEach(item->{
                LwgyAbnormalAction lwgyAbnormalAction = new LwgyAbnormalAction();
                //添加学院信息
                lwgyAbnormalAction.setStudentid(item.getId());
                lwgyAbnormalAction.setStudentXy(item.getStudentCollege());
                lwgyAbnormalAction.setStudentZy(item.getStudentMajor());
                lwgyAbnormalAction.setStudentBj(item.getStudentClass());
                lwgyAbnormalAction.setStudentSex(item.getStudentSex());
                List<LwgyBaseBed> bedsList = bedList.stream().filter(d ->
                        d.getStudentId().equals(item.getId())).collect(Collectors.toList());
                if(oConvertUtils.isNotEmpty(bedsList)  && bedsList.size()>0){
                    //添加床位信息
                    LwgyBaseBed lwgyBaseBed = bedsList.get(0);
                    lwgyAbnormalAction.setCampus(lwgyBaseBed.getCampusId());
                    lwgyAbnormalAction.setBuildingNum(lwgyBaseBed.getBuildingId());
                    lwgyAbnormalAction.setUnit(lwgyBaseBed.getUnitId());
                    lwgyAbnormalAction.setRoomNum(lwgyBaseBed.getRoomId());
                    lwgyAbnormalAction.setBedNum(lwgyBaseBed.getId());
                }

                lwgyAbnormalAction.setStuStatus("3");//abnormal_inout 字典 1晚归，2未归 3异常（长时间未出和未归）
                lwgyAbnormalAction.setStudentName(item.getStudentName());
                lwgyAbnormalAction.setStudentNumber(item.getStudentNumber());
                lwgyAbnormalAction.setLastIntoStatus(item.getLastDirection());

                String str1 = item.getLastDirectionTime();
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date myDate1 = null;
                try {
                    myDate1 = sdf1.parse(str1);
                }catch (Exception e){
                    e.printStackTrace();
                }

                lwgyAbnormalAction.setLastIntoTime(myDate1);
                endList.add(lwgyAbnormalAction);
            });
            lwgyAbnormalActionService.saveBatch(endList);
            exportUnusualExcel(endList);

        }
    }
    @GetMapping(value = "/exportUnusualExcel", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseEntity<InputStreamResource> exportUnusualExcel(@RequestParam("endList") List<LwgyAbnormalAction> endList) throws IOException {
//    XWPFDocument document = new XWPFDocument();
//    XWPFParagraph paragraph = document.createParagraph();
//    XWPFRun run = paragraph.createRun();
//    for (LwgyAbnormalAction lwgyAbnormalAction : endList) {
//        run.setText(String.valueOf(lwgyAbnormalAction));
//        run.addBreak(BreakType.TEXT_WRAPPING);
//    }
        Workbook workbook = new XSSFWorkbook(); // 新建一个工作簿对象
        Sheet sheet = workbook.createSheet("Student"); // 创建一个工作表对象
        // 创建表头行
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("姓名");
        headerRow.createCell(1).setCellValue("性别");
        headerRow.createCell(2).setCellValue("学号");
        headerRow.createCell(3).setCellValue("校区");
        headerRow.createCell(4).setCellValue("学院");
        headerRow.createCell(5).setCellValue("班级");
        headerRow.createCell(6).setCellValue("楼号");
        headerRow.createCell(7).setCellValue("单元");
        headerRow.createCell(8).setCellValue("房间号");
        headerRow.createCell(9).setCellValue("床位号");
        headerRow.createCell(10).setCellValue("学生异动状态");
        headerRow.createCell(11).setCellValue("最后进出状态");
        headerRow.createCell(12).setCellValue("最后进出时间");

//填充数据行
        for (int i = 0; i< endList.size();i++){
            LwgyAbnormalAction lwgyAbnormalAction = endList.get(i);
            Row dataRow =sheet.createRow(i+1);
            dataRow.createCell(0).setCellValue(lwgyAbnormalAction.getStudentName());
            dataRow.createCell(2).setCellValue(lwgyAbnormalAction.getStudentNumber());
            String sex = lwgyAbnormalAction.getStudentSex();
            String gender;
            if (sex.equals("1")){
                gender = "男";
            }else if (sex.equals("2")){
                gender = "女";
            }else{
                gender = "未知";
            }
            String lastIntoStatus = lwgyAbnormalAction.getLastIntoStatus();
            String status;
            if (lastIntoStatus.equals("1")){
                status = "进";
            }else if (lastIntoStatus.equals("2")){
                status = "出";
            }else {
                status = "未知";
            }
            String studentStatus = lwgyAbnormalAction.getStuStatus();
            String stustatus;
            if (studentStatus.equals("2")){
                stustatus = "未归";
            }else {
                stustatus = "未知";
            }
            dataRow.createCell(1).setCellValue(gender);
            dataRow.createCell(3).setCellValue(lwgyAbnormalAction.getCampus());
            dataRow.createCell(4).setCellValue(lwgyAbnormalAction.getStudentXy());
            dataRow.createCell(5).setCellValue(lwgyAbnormalAction.getStudentBj());
            dataRow.createCell(6).setCellValue(lwgyAbnormalAction.getBuildingNum());
            dataRow.createCell(7).setCellValue(lwgyAbnormalAction.getUnit());
            dataRow.createCell(8).setCellValue(lwgyAbnormalAction.getRoomNum());
            dataRow.createCell(9).setCellValue(lwgyAbnormalAction.getBedNum());
            dataRow.createCell(10).setCellValue(stustatus);
            dataRow.createCell(11).setCellValue(status);
            dataRow.createCell(12).setCellValue(lwgyAbnormalAction.getLastIntoTime());
        }
        // 指定要保存的路径和文件名word
//    String filePath = "C:\\Users\\Lenovo\\Desktop\\test\\test.xlsx";
//    FileOutputStream fileOut = new FileOutputStream(filePath);
//    document.write(fileOut);
//    fileOut.close();
        //指定要保存的路径和文件名excel
        File file = new File("C:\\Users\\Lenovo\\Desktop\\test\\异常记录.xlsx");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        workbook.write(fileOutputStream); // 将工作簿写入文件输出流中
        fileOutputStream.close(); // 关闭文件输出流

        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
        return ResponseEntity.ok()
                .header("Content-Disposition", "attachment; filename=enlist.xlsx")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }
}
